/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.seari.semodbus.server;

import com.ghgande.j2mod.modbus.ModbusCoupler;
import com.ghgande.j2mod.modbus.procimg.ProcessImage;
import com.ghgande.j2mod.modbus.procimg.Register;
import com.ghgande.j2mod.modbus.procimg.SimpleProcessImage;
import com.seari.semodbus.bean.VirtualModbus;
import com.seari.semodbus.main.MainController;
import com.seari.semodbus.utils.JedisPoolUtils;
import java.sql.Time;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Pipeline;

/**
 *
 * @author Rainbow
 */
public class RefreshTask implements Runnable
{

    @Override
    public void run()
    {
        Jedis redisClient = JedisPoolUtils.getJedis();
        Pipeline pipeline = redisClient.pipelined();
        int startPos = VirtualModbus.posList.get(0);
        int endPos = VirtualModbus.posList.get(VirtualModbus.posList.size()-1);
        ProcessImage pi = ModbusCoupler.getReference().getProcessImage(1);
        Register[] registers = pi.getRegisterRange(startPos, endPos+1);
        while (true)
        {            
            for (int i = startPos; i <= endPos; i++)
            {
                pipeline.get("v" + i);
            }
            List<Object> results = pipeline.syncAndReturnAll();
            for(int j = 0;j < results.size();j++)
            {
                Object value = results.get(j);
                registers[j].setValue(Integer.parseInt(value.toString()));
//                System.out.println(registers);
            }
//            try
//            {
//                TimeUnit.SECONDS.sleep(1);
//            } catch (InterruptedException ex)
//            {
//                Logger.getLogger(RefreshTask.class.getName()).log(Level.SEVERE, null, ex);
//            }
        }

    }
    
}
